package com.company.module.net.factory;

import android.util.Log;

import com.company.module.net.BuildConfig;
import com.company.module.net.bean.BaseBean;
import com.company.module.net.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;


/**
 * @author sixbing
 * on 2018/4/24 0024 下午 2:54
 * description :
 */

public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, Object> {

    private final Gson gson;
    private final TypeAdapter<T> adapter;
    private final String TAG = "GsonResponseBody";

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException, JsonSyntaxException {
        //ResponseData中的流只能使用一次，我们先将流中的数据读出在byte数组中。这个方法中已经关闭了ResponseBody,所以不需要再关闭了
        byte[] valueBytes = value.bytes();
        JsonReader jsonReader = null;
        if (StringUtils.isNull(value)) {
            handlerTokenTimeOut(valueBytes, "null");
            return null;
        }
        InputStreamReader charReader = null;
        try {//try中的为正常流程代码
            charReader = new InputStreamReader(new ByteArrayInputStream(valueBytes), "UTF-8");//后面的charset根据服务端的编码来定
            jsonReader = gson.newJsonReader(charReader);//原来是使用value.charStream
            Object obj = adapter.read(jsonReader);
            handlerTokenTimeOut(valueBytes, "true");
            return (T) obj;
        } catch (JsonSyntaxException e) {//当catch到这个错误说明gson解析错误，基本肯定是服务端responseData的问题，此时我们自己解析
            e.printStackTrace();
            BaseBean baseBean = new Gson().fromJson(new String(valueBytes), BaseBean.class);
            handlerTokenTimeOut(valueBytes, "false1");
            return (T) baseBean;
        } catch (Exception e) {
            e.printStackTrace();
            handlerTokenTimeOut(valueBytes, "false2");
            return null;
        } finally {
            if (jsonReader != null)
                jsonReader.close();
        }
    }

    private void handlerTokenTimeOut(byte[] obj, String flag) {
        if (BuildConfig.DEBUG) {
            if (StringUtils.isNull(obj)) {
                Log.e(TAG, flag + "=============>>\n" + obj);
            } else {
                String s = new String(obj);
                Log.e(TAG, flag + "=============>>\n" + s);
            }
        }
    }
}
